package com.axjy.service.impl;

import com.axjy.vo.PageVo;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service("baseService")
public class BaseServiceImpl {

    @PersistenceContext
    private EntityManager entityManager;

    private Session session;

    {
        session=entityManager.unwrap(Session.class);
    }

    /*假设传过来的语句(可以是普通查询，也可以是join fetch关联查询）
    *  select h from House h join fetch h.street s join fetch s.district d join fetch h.type t where h.title=:title
    *   and s.id=:streetId and t.id=:typeId and h.price>=:startPrice and h.price<:endPrice
    *
    * */
    public PageVo searchPagination(String hql,Object dto,Integer offset,Integer pageSize){
        Query query= session.createQuery(hql);
        query.setProperties(dto);
        query.setFirstResult(offset).setMaxResults(pageSize);
        List rows=query.list();
        PageVo pageVo=new PageVo();
        pageVo.setRows(rows);
        pageVo.setTotal(this.getTotal(hql,dto));
        return pageVo;
    }

    private long getTotal(String hql,Object dto){
        int index=hql.indexOf("from");
        String countHql="select count(*) "+ hql.substring(index).replace("fetch","");
        Object count=session.createQuery(countHql).setProperties(dto).uniqueResult();
        return Long.parseLong(count.toString());
    }



}
